<!doctype html>
<meta charset=UTF-8 />
<body>
<h1 id="status">Processing...</h1>
<a href="index.html">Take me back home!</a>

<script>
// Code from Google. At least I understand it...
// So, this code takes the hash of the location, and then
//   splits it into parts using regex.exec() into the
//   params object.
var params = {}, queryString = location.hash.substring(1),
    regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(queryString)) {
  params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// end

// This is pretty much the biggest library I use
function $(id){return document.getElementById(id)};
function crossDomainReq() {
  try {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) return xhr;
  } catch(e) {}

  try {
    return new XDomainRequest();
  } catch(e) {}

  $("status").innerHTML="Error: cross-domain requests not supported";
  throw new Error();
}

// Set up the access token and client id
var access_token = "",
  client_id = "578737917000.apps.googleusercontent.com";

if (params.error) {
  // Goodness me, there's an error
  $("status").innerHTML="Invalid query parameters: "+params.error;
  if(params.error=="access_denied") {
    $("status").innerHTML += "\n\nWhich means you didn't allow access. Hooray.";
  }
} else {
  access_token = params.access_token;

  // YOU'D BETTER NOT ABUSE THIS!!! but who woould? I guess
  //   it'd be more likely that someone would sabatoge it. Oh well.
  var xhr = crossDomainReq();
  xhr.open("GET","http://gengkev.tk/proxy/apps.php?client_id="+client_id+"&proxy_url="
    + escape("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=")+access_token,true);
  xhr.onload=function(){
      var response = xhr.responseText;

      // replace any leading text
      response = response.replace(/^\s*/,"");

      // anything not in the main { ... } dies
      // cos my silly webhost inserts some HTML
      // code... oh right, I should set the type
      // to application/json * facepalm * but I'll
      // keep it here anyhow.
      response = (/\{[\s\S]*\}/igm).exec(response)[0];

      // polyfilled.
      response = JSON.parse(response);
      if (response.audience != "578737917000.apps.googleusercontent.com") {
        // I still don't know why I have to do this
        $("status").innerHTML="Token validation failed (wrong clientid): "+response.audience;
      }
      else {
        // hurrah
        location.replace("index.html");
      }
  }
  xhr.onerror=function(e){
    $("status").innerHTML="Token validation failed: request error ("+e+")";
  }
  xhr.send();
}
// oh look it's a basic jsonp loader helper thingy
function jsonp(url) {
  var s = document.createElement("script");
  s.async=true;
  s.src=url;
  document.head.appendChild(s);
}


</script>
</body>